package com.ant.business.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ant.business.system.entity.User;
import com.ant.business.system.entity.UserToken;
import com.ant.business.system.mapper.UserTokenMapper;
import com.ant.business.system.service.UserTokenService;
import com.ant.business.system.vo.UserVo;
import com.ant.common.exceptions.BusinessException;
import com.ant.common.utils.FastMap;
import com.ant.common.utils.LocalBeanUtil;
import com.ant.common.utils.UserThreadLocal;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 用户tokenService实现类
 *
 * @description
 * @create 2023-07-16 16:57:44
 */
@Service("userTokenService")
@Transactional(rollbackFor = Throwable.class)
public class UserTokenServiceImpl extends ServiceImpl<UserTokenMapper, UserToken> implements UserTokenService {

    private final UserTokenMapper userTokenMapper;

    public UserTokenServiceImpl(UserTokenMapper userTokenMapper) {
        this.userTokenMapper = userTokenMapper;
    }

    /**
     * 分页查询列表
     *
     * @param page  页数
     * @param limit 条数
     * @param param 参数
     * @return PageInfo
     */
    @Override
    public PageInfo<UserToken> getList(int page, int limit, FastMap param) {
        QueryWrapper<UserToken> wrapper = new QueryWrapper<>();
        PageHelper.startPage(page, limit);
        List<UserToken> list = userTokenMapper.selectList(wrapper);
        return new PageInfo<UserToken>(list);
    }

    /**
     * 分页查询列表
     *
     * @param param 参数
     * @return PageInfo
     */
    @Override
    public List<UserToken> getAllList(FastMap param) {
        QueryWrapper<UserToken> wrapper = new QueryWrapper<>();
        return userTokenMapper.selectList(wrapper);
    }

    /**
     * 通过编号查询
     *
     * @param primaryKey
     * @return
     */
    @Override
    @SneakyThrows
    public UserToken getById(String primaryKey) {
        UserToken userToken = userTokenMapper.selectById(primaryKey);
        if (Objects.isNull(userToken)) {
            throw new BusinessException("用户token编号不正确");
        }
        return userToken;
    }

    /**
     * 新增信息
     *
     * @param userToken userToken
     */
    @Override
    @SneakyThrows
    public void saveOne(UserToken userToken) {
        LocalBeanUtil.setLoginUserInfo(userToken, UserThreadLocal.getUser().getUserName(), UserThreadLocal.getUser().getUnitId());
        int count = userTokenMapper.insert(userToken);
        if (count != 1) {
            throw new BusinessException("用户token保存失败");
        }
    }

    /**
     * 更新信息
     *
     * @param userToken userToken
     */
    @Override
    @SneakyThrows
    public void update(UserToken userToken) {
        LocalBeanUtil.updateLoginUserInfo(userToken, UserThreadLocal.getUser().getUserName());
        int count = userTokenMapper.updateById(userToken);
        if (count != 1) {
            throw new BusinessException("用户token更新失败");
        }
    }

    /**
     * 删除信息
     *
     * @param primaryKey id
     */
    @Override
    @SneakyThrows
    public void delete(String primaryKey) {
        UserToken userToken = userTokenMapper.selectById(primaryKey);
        if (Objects.isNull(userToken)) {
            throw new BusinessException("未通过编号找到用户token");
        }
        int count = userTokenMapper.deleteById(primaryKey);
        if (count != 1) {
            throw new BusinessException("用户token删除失败");
        }
    }

    /**
     * 通过token查询用户信息，可用redis替换
     *
     * @param token
     * @return
     */
    @Override
    public UserVo getUserInfo(String token) {
        QueryWrapper<UserToken> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        List<UserToken> list = this.list(wrapper);
        if (list.size() > 0) {
            UserToken userToken = list.get(0);
            String userInfo = userToken.getUserInfo();
            FastMap fastMap = FastMap.fromObject(userInfo);
            UserVo userVo = new UserVo();
            FastMap.mapToBean(fastMap, userVo);
            return userVo;
        }
        return null;
    }

    /**
     * 保存token信息，可用redis替换
     *
     * @param user
     * @param token
     */
    @Override
    public void saveToken(User user, String token) {
        /*QueryWrapper<UserToken> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getUserId());
        List<UserToken> list = this.list(wrapper);
        if (list.size() > 0) {
            UserToken userToken = list.get(0);
            userToken.setToken(token);
            userToken.setExpireTime(System.currentTimeMillis() + (1000 * 60 * 60 * 24));
            userToken.setEditTime(System.currentTimeMillis());
            userToken.setEditor(user.getUserName());
            this.updateById(userToken);
        } else {*/
            UserToken userToken = new UserToken();
            userToken.setUserId(user.getUserId());
            userToken.setUserInfo(JSON.toJSONString(user));
            userToken.setToken(token);
            userToken.setCreateTime(System.currentTimeMillis());
            userToken.setCreator(user.getUserName());
            userToken.setEditTime(System.currentTimeMillis());
            userToken.setEditor(user.getUserName());
            userToken.setExpireTime(System.currentTimeMillis() + (1000 * 60 * 60 * 24));
            userToken.setUnitId(user.getUnitId());
            this.save(userToken);
        //}
    }

    @Override
    public void deleteToken(String token) {
        QueryWrapper<UserToken> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        this.remove(wrapper);
    }
}
